// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2025-02-08

package sell_refund

import (
    "context"
    "gitee.com/go-libs/log"
    "integration/app/lib/conf"
    "integration/app/lib/nod/crmeb"
    "integration/app/models"
)

// Entity
// 销售订单入参.
//
//   {
//      "form":{
//          "id":0,
//          "customer":82,
//          "time":"2025-02-13",
//          "number":"XHTHD1018",
//          "total":13,
//          "discount":"0",
//          "actual":13,
//          "money":13,
//          "account":13,
//          "cost":0,
//          "frame":1,
//          "user":4,
//          "person":"",
//          "logistic":{"key":"auto","number":""},
//          "file":[],
//          "field":{"a":"","b":"","c":"","d":"","e":""},
//          "data":"",
//          "amount":0,
//          "examine":0,
//          "check":0,
//          "nucleus":0,
//          "cse":0,
//          "invoice":0
//      },
//      "info":[
//          {
//              "goods":369,
//              "spec":"",
//              "cell":116,
//              "warehouse":26,
//              "price":"13",
//              "tpe":13,
//              "nums":1,
//              "serial":[],
//              "batch":"",
//              "mfg":"",
//              "discount":"0",
//              "dsc":0,
//              "total":13,
//              "tax":"0",
//              "tat":0,
//              "tpt":13,
//              "cost":"0",
//              "field":{"a":"","b":"","c":"","d":"","e":""},
//              "data":"",
//              "relation":{"state":false}
//          }
//      ],
//      "cost":[]
//  }
type Entity struct {
    Cost  []any    `json:"cost"`
    Goods []*Goods `json:"info"`
    Order *Order   `json:"form"`
}

func New() *Entity {
    return &Entity{
        Order: NewOrder(),
        Goods: make([]*Goods, 0),
        Cost:  make([]any, 0),
    }
}

// Parse
// 解析订单参数.
func (o *Entity) Parse(ctx context.Context, agent *conf.ErpAgent, order *models.Order, carts []*models.OrderCartInfo) (err error) {
    if err = o.parseGoods(ctx, order, carts); err == nil {
        err = o.parseOrder(ctx, agent, order)
    }
    return
}

// 遍历商品.
func (o *Entity) parseGoods(cts context.Context, order *models.Order, carts []*models.OrderCartInfo) (err error) {
    var (
        ctx   = log.NewContextForChildInfo(cts, `crmeb cart iterate: count="%d"`, len(carts))
        goods *Goods
    )
    for i, cart := range carts {
        if goods, err = o.parseGoodsInfo(ctx, order, i, cart); err != nil {
            break
        }
        o.Goods = append(o.Goods, goods)
    }
    return
}

// 解析商品.
func (o *Entity) parseGoodsInfo(cts context.Context, order *models.Order, index int, cart *models.OrderCartInfo) (goods *Goods, err error) {
    var (
        ctx  = log.NewContextForChildInfo(cts, `crmeb cart parser: index="%d", body=%s`, index, cart.CartInfo)
        info crmeb.CartInfo
    )

    // 1. 监听结束.
    defer func() {
        if err != nil {
            log.Errorfc(ctx, `crmeb cart parsed: error="%v"`, err)
        }
    }()

    // 2. 解析数据.
    if info, err = crmeb.NewCartInfo(cart.CartInfo); err == nil {
        log.Infofc(ctx, `goods in crmeb: product_id="%v", product_code="%s", product_name="%s", quality="%v", price="%v"`, info.Product.Id, info.GenerateCode(), info.GenerateName(), info.Quality, info.Price)
        goods = NewGoods()
        if err = goods.With(ctx, order, info); err == nil {
            log.Infofc(ctx, `goods in erp: goods_id="%v", goods_tax="%v", goods_warehouse="%v"`, goods.GoodsId, goods.Tax, goods.Warehouse)
        }
    }
    return
}

// 解析订单.
func (o *Entity) parseOrder(cts context.Context, agent *conf.ErpAgent, order *models.Order) (err error) {
    var ctx = log.NewContextForChildInfo(cts, `crmeb order parse`)
    err = o.Order.With(ctx, agent, order, o.Goods)
    return
}
